import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import type { RouteLocationNormalized } from 'vue-router'

export interface TabInfo {
  path: string
  name: string
  title: string
  icon: string
  closable: boolean
}

export const useTabsStore = defineStore('tabs-store', () => {
  const tabs = ref<TabInfo[]>([])
  const activeTabPath = ref('')

  /**
   * 需缓存的组件name列表
   */

  const cacheViews = computed(() => tabs.value.map((tab) => tab.name))

  /**
   * 新增一个标签页
   */

  const addTab = (route: RouteLocationNormalized) => {
    const { path, name, meta } = route
    const title = meta.title || 'New Tab'
    const icon = meta.icon || 'notes'
    const closable = (meta.closable as boolean | undefined) ?? true

    const index = tabs.value.findIndex((tab) => tab.path === path)
    if (index === -1) {
      tabs.value.push({ path, name: name as string, title, icon, closable })
    }
    // 设置激活当前标签
    activeTabPath.value = path
  }

  /**
   * 移除一个标签页
   */

  const removeTab = (path: string) => {
    const index = tabs.value.findIndex((tab) => tab.path === path)
    if (index === -1) return

    // 如果关闭的是当前激活标签，则需要确定下一个激活标签
    if (activeTabPath.value === path) {
      const nextTab = tabs.value[index + 1] || tabs.value[index - 1]

      if (nextTab) {
        activeTabPath.value = nextTab.path
      }
    }
    // 从数组中移除
    tabs.value.splice(index, 1)
  }

  /**
   * 激活标签页
  d*/

  const setActiveTab = (path: string) => (activeTabPath.value = path)

  return {
    // state
    tabs,
    activeTabPath,

    // getter
    cacheViews,

    // action
    addTab,
    removeTab,
    setActiveTab,
  }
})
